package cn.com.fssg.platform.base.handler.impl.cl.fuju;

import cn.com.fssg.platform.base.handler.TaskHandler;
import cn.com.fssg.platform.biz.BizUtil;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ClFujuApplyTaskHandler implements TaskHandler {

    private static final Logger log = LoggerFactory.getLogger(ClFujuApplyTaskHandler.class);
    private static final String APPLY_TYPE = "APPLY_FUJU";
    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantJdbcTemplate("CJRLHHConnString");
//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public boolean beforeSubmit(Task task) {
        return false;
    }

    @Override
    public boolean afterSubmit(Task oldTask, List<Task> newTasks) {
        boolean result = false;
        String proInstId;
        if (CollectionUtils.isEmpty(newTasks)) { //当前是最后一个节点
            proInstId = oldTask.getProcessInstanceId();

        } else {
            //选择下一个节点
            proInstId = newTasks.get(0).getProcessInstanceId();
        }
        //获取业务主表ID
        String querySql = String.format("select distinct(biz_key) from pxone.actex_hi_procinst where id = '%s'",proInstId);
        Map<String,Object> paramMap = new HashMap<>();
        Map<String, Object> map = jdbcTemplate.queryForMap(querySql, paramMap);
        //业务表主键
        String id = (String) map.get("biz_key");
        if (!ObjectUtils.isEmpty(id)) {
            querySql = String.format("select * from cl_apply_fuju where id = '%s'", id);
            map = jdbcTemplate.queryForMap(querySql, paramMap);
            try {
                insertHistory(map);
                createFujuDyq(map);
                result = true;
            } catch (Exception e) {
                log.error(e.getMessage());
                result = false;
            }
        }
        return result;
    }

    /**
     * 计入历史申请
     * @param dataMap
     */
    private void insertHistory(Map<String, Object> dataMap) {
        if (!ObjectUtils.isEmpty(dataMap)) {
            //APPLY_XUNLIAN
            String sql = "insert into cl_apply_history (" +
                    "id, apply_time, jhr_idcard, apply_id," +
                    "shenpi_no, cjr_name, apply_type, " +
                    "create_by, create_time, update_by, update_time, " +
                    "finish, flow_status_describe, cjr_sex, cjr_birthday, " +
                    "cjr_minzu, cjr_hukou, cjr_idcard, has_cjr_card, " +
                    "cjr_num, cjr_type, cjr_type_name, cjr_cj_level, " +
                    "cjr_bx, cjr_jjqk, cjr_address, cjr_jhr, " +
                    "cjr_jhr_gx, cjr_jhr_phone, cjr_service_type, " +
                    "cjr_service_cat, apply_from, apply_user, " +
                    "submit_time, shenhe_time, effect_from, effect_to" +
                    ") values (" +
                    ":id, :apply_time, :jhr_idcard, :apply_id," +
                    ":shenpi_no, :cjr_name, :apply_type, " +
                    ":create_by, :create_time, :update_by, :update_time, " +
                    ":finish, :flow_status_describe, :cjr_sex, :cjr_birthday, " +
                    ":cjr_minzu, :cjr_hukou, :cjr_idcard, :has_cjr_card, " +
                    ":cjr_num, :cjr_type, :cjr_type_name, :cjr_cj_level, " +
                    ":cjr_bx, :cjr_jjqk, :cjr_address, :cjr_jhr, " +
                    ":cjr_jhr_gx, :cjr_jhr_phone, :cjr_service_type, " +
                    ":cjr_service_cat, :apply_from, :apply_user, " +
                    ":submit_time, :shenhe_time, :effect_from, :effect_to)";
            Map<String, Object> paraMap = new HashMap<>();
            paraMap.put("id", BizUtil.cur().getSnowflakeIdStr());
            paraMap.put("apply_time", dataMap.get("apply_time"));
            paraMap.put("jhr_idcard", dataMap.get("jhr_idcard"));
            paraMap.put("apply_id", dataMap.get("id"));
            paraMap.put("shenpi_no", dataMap.get("shenpi_no"));
            paraMap.put("cjr_name", dataMap.get("cjr_name"));
            paraMap.put("apply_type", APPLY_TYPE);
            paraMap.put("create_by", dataMap.get("create_by"));
            paraMap.put("create_time", dataMap.get("create_time"));
            paraMap.put("update_by", dataMap.get("update_by"));
            paraMap.put("update_time", dataMap.get("update_time"));
            paraMap.put("finish", dataMap.get("finish"));
            paraMap.put("flow_status_describe", dataMap.get("flow_status_describe"));
            paraMap.put("cjr_sex", dataMap.get("cjr_sex"));
            paraMap.put("cjr_birthday", dataMap.get("cjr_birthday"));
            paraMap.put("cjr_minzu", dataMap.get("cjr_minzu"));
            paraMap.put("cjr_hukou", dataMap.get("cjr_hukou"));
            paraMap.put("cjr_idcard", dataMap.get("cjr_idcard"));
            paraMap.put("has_cjr_card", dataMap.get("has_cjr_card"));
            paraMap.put("cjr_num", dataMap.get("cjr_num"));
            paraMap.put("cjr_type", dataMap.get("cjr_type"));
            paraMap.put("cjr_type_name", dataMap.get("cjr_type_name"));
            paraMap.put("cjr_cj_level", dataMap.get("cjr_cj_level"));
            paraMap.put("cjr_bx", dataMap.get("cjr_bx"));
            paraMap.put("cjr_jjqk", dataMap.get("cjr_jjqk"));
            paraMap.put("cjr_address", dataMap.get("cjr_address"));
            paraMap.put("cjr_jhr", dataMap.get("cjr_jhr"));
            paraMap.put("cjr_jhr_gx", dataMap.get("cjr_jhr_gx"));
            paraMap.put("cjr_jhr_phone", dataMap.get("cjr_jhr_phone"));
            paraMap.put("cjr_service_type", dataMap.get("cjr_service_type"));
            paraMap.put("cjr_service_cat", dataMap.get("cjr_service_cat"));
            paraMap.put("apply_from", dataMap.get("apply_from"));
            paraMap.put("apply_user", dataMap.get("apply_user"));
            paraMap.put("submit_time", dataMap.get("submit_time"));
            paraMap.put("shenhe_time", timeFormat.format(new Date()));
            paraMap.put("effect_from", dataMap.get("effect_from"));
            paraMap.put("effect_to", dataMap.get("effect_to"));
            jdbcTemplate.update(sql, paraMap);
        }
    }

    /**
     * 生成代用券
     * @param fujuMap
     * @throws Exception
     */
    private void createFujuDyq(Map<String, Object> fujuMap) throws Exception{
        if (ObjectUtils.isEmpty(fujuMap)) {
            return;
        }
        Object id = fujuMap.get("id");
        if (ObjectUtils.isEmpty(id)) {
            return;
        }
        String applyId = (String) id;
        String shenpiNo = (String) fujuMap.get("shenpi_no");
        String queryItemSql = "select * from cl_apply_fuju_item where apply_id = :applyId";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("applyId", applyId);
        String historySql = "select * from cl_apply_history where apply_id = :applyId";
        Map<String, Object> historyMap = jdbcTemplate.queryForMap(historySql, paramMap);
        List<Map<String, Object>> items = jdbcTemplate.queryForList(queryItemSql, paramMap);
        if (!CollectionUtils.isEmpty(items)) {
            String sql = "insert into cl_dyq (" +
                    "id, wt, bus_id, shenpi_no," +
                    "cjr_name, cjr_idcard, code, " +
                    "used_count, history_id, apply_type,max_count, " +
                    "shenpi_no_sub, cjr_hukou, cjr_service_type, cjr_service_cat," +
                    "dyq_money, invalid, invalid_time,cjr_sex," +
                    "cjr_birthday, cjr_type, cjr_cj_level, apply_time," +
                    "create_by, create_time, update_by, update_time," +
                    "del_flag) values(" +
                    " :id, :wt, :bus_id, :shenpi_no," +
                    " :cjr_name, :cjr_idcard, :code, " +
                    " :used_count, :history_id, :apply_type, :max_count," +
                    " :shenpi_no_sub, :cjr_hukou, :cjr_service_type, :cjr_service_cat," +
                    " :dyq_money, :invalid, :invalid_time,:cjr_sex," +
                    " :cjr_birthday, :cjr_type, :cjr_cj_level, :apply_time," +
                    " :create_by, :create_time, :update_by, :update_time," +
                    " :del_flag)";
            int index = 1;
            for (Map<String, Object> item : items) {
                String code = "DYQ" + shenpiNo + "_" + index;
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("id", BizUtil.cur().getSnowflakeIdStr());
                itemMap.put("wt", "0");
                itemMap.put("bus_id", applyId);
                itemMap.put("shenpi_no", shenpiNo);
                itemMap.put("cjr_name", fujuMap.get("cjr_name"));
                itemMap.put("cjr_idcard", fujuMap.get("cjr_idcard"));
                itemMap.put("code", code);
                itemMap.put("used_count", 0);
                itemMap.put("history_id", ObjectUtils.isEmpty(historyMap)? null : historyMap.get("id"));
                itemMap.put("apply_type", APPLY_TYPE);
                itemMap.put("max_count", 1);
                itemMap.put("shenpi_no_sub", shenpiNo + "_" + index);
                itemMap.put("cjr_hukou", fujuMap.get("cjr_hukou"));
                itemMap.put("cjr_service_type", fujuMap.get("cjr_service_type"));
                itemMap.put("cjr_service_cat", fujuMap.get("cjr_service_cat"));
                itemMap.put("dyq_money", item.get("money"));
                itemMap.put("invalid", "0");
                itemMap.put("invalid_time", null);
                itemMap.put("cjr_sex", fujuMap.get("cjr_sex"));
                itemMap.put("cjr_birthday", fujuMap.get("cjr_birthday"));
                itemMap.put("cjr_type", fujuMap.get("cjr_type"));
                itemMap.put("cjr_cj_level", fujuMap.get("cjr_cj_level"));
                itemMap.put("apply_time", fujuMap.get("apply_time"));
                itemMap.put("create_by", BizUtil.cur().curUserId());
                itemMap.put("create_time", timeFormat.format(new Date()));
                itemMap.put("update_by", BizUtil.cur().curUserId());
                itemMap.put("update_time", timeFormat.format(new Date()));
                itemMap.put("del_flag", 0);
                jdbcTemplate.update(sql, itemMap);
                index++;
            }
        }
    }


}
